package me.zhengjie.common.utils

import org.springframework.data.domain.Page

/**
 * 分页工具
 * @author Kuki Wu
 * @date 2018-12-10
 */
object PageUtil : cn.hutool.core.util.PageUtil() {

    fun paging(page: Int, size: Int, list: List<*>): List<*> {
        return toPage(page, size, list)
    }

    /**
     * List 分页
     */
    fun toPage(page: Int, size: Int, list: List<*>): List<*> {
        val fromIndex = page * size
        val toIndex = page * size + size
        return if (fromIndex > list.size) {
            ArrayList<Any?>()
        } else if (toIndex >= list.size) {
            list.subList(fromIndex, list.size)
        } else {
            list.subList(fromIndex, toIndex)
        }
    }


    /**
     * Page 数据处理，预防redis反序列化报错
     */
    fun <T> toPage(page: Page<T>): PageResult<T> {
        return PageResult(page.content, page.totalElements)
    }

    /**
     * 自定义分页
     */
    fun <T> toPage(list: List<T>?, totalElements: Long): PageResult<T> {
        return PageResult(list, totalElements)
    }

    /**
     * 返回空数据
     */
    fun <T> noData(): PageResult<T>? {
        return PageResult(null, 0)
    }
}